package com.zx.cashiersystem.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.SocketResponsePacket;
import com.zx.cashiersystem.activity.BaseActivity;

import java.util.List;

/**
 * Created by stone on 2017/1/11.
 */

public class ClientSocketService extends Service implements SocketClient.SocketDelegate {
    public static boolean is_running = false;
    private static final String TAG = "ClientSocketService";
    private ClientSockets socketClient;

    //    private MessageCenterDaoManager daoManager;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        is_running = true;
//        daoManager = new MessageCenterDaoManager();
        initSocket();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null != intent) {
            if (intent.getStringExtra("msg") != null)
                socketClient.sendData(intent.getStringExtra("msg"));
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void initSocket() {
        socketClient = new ClientSockets();
        socketClient.registerConnectListener(this);
        socketClient.connect();
    }


    @Override
    public void onConnected(SocketClient client) {
        Log.e(TAG, "onConnected: ");
        socketClient.sendData("{\"type\":\"boss_login\",\"content\":\"1\"}");
    }

    @Override
    public void onDisconnected(SocketClient client) {
        Log.e(TAG, "onDisconnected: ");
        if (client.getRunningSocket() == null) {
            //一段时间没消息，重新连接
            socketClient = null;
            initSocket();
            socketClient.connect();
        } else {
            socketClient.connect();
        }
    }

    @Override
    public void onResponse(SocketClient client, @NonNull SocketResponsePacket responsePacket) {
        String content = responsePacket.getMessage();
        if (content != null) {
            Message msg = getMessage();
            msg.what = 1;
            msg.obj = content;
            handler.sendMessage(msg);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String s1 = (String) msg.obj;
                    List<String> list = ReceiveMessage.splite(s1);
                    for (String str : list) {
                        Message msg1 = getMessage();
                        msg1.what = 2;
                        msg1.obj = str;
                        handler.sendMessage(msg1);
                    }
                    break;
                case 2:
                    String s2 = (String) msg.obj;
                    try {
                        doData(s2);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    };

    public void doData(String str) {
        MyMessages m = JSON.parseObject(str, new TypeReference<MyMessages>() {
        });
        Intent intent;
        switch (m.getType()) {
            case "ping":
                break;
            case "bind":
                break;
            case "stock_warning":
                break;
            case "web":
                intent = new Intent();
                intent.setAction(BaseActivity.MSG_BROCARSTRECEIVER);
                intent.putExtra("msg", str);
                sendBroadcast(intent);
                socketClient.sendData("{\"type\":\"res\",\"content\":{\"content\":" + JSON.toJSONString(m.getContent()) + "}}");
                break;
            default:

                Log.e(TAG, "doData: " + str);
                break;
        }
    }

    public Message getMessage() {
        return new Message();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        is_running = false;
        socketClient.unregisterConnectListener(this);
        socketClient.disconnect();
    }
}
